<template>
  <div>
    <div id="tui-image-editor" class="tui-image-editor"></div>
    <div class="tui-image-editor-controls mobile">
      <p class="msg">Menu Scrolling <b>Left ⇔ Right</b></p>
      <ul class="scrollable">
        <li v-for="item in bottomMenu" :key="item.id" class="menu-item">
          <button
            :id="'btn-' + item.id"
            :class="['menu-button', { disabled: item.disabled }]"
            @click="($event) => handleMenuClick($event.target, item.id)"
          >
            {{ item.label }}
          </button>
          <div v-if="item.children && item.children.length > 0" class="submenu">
            <button class="btn-prev" @click="menuHide">
              <i class="el-icon-arrow-left" />
            </button>
            <ul class="scrollable">
              <li
                v-for="child in item.children"
                :key="child.id"
                class="menu-item"
              >
                <button
                  class="submenu-button"
                  @click="handleSubMenuClick(item.id + '-' + child.id, $event)"
                >
                  {{ child.label }}
                </button>
                <!-- 颜色选择 -->
                <div v-if="child.colorpicker" class="hiddenmenu">
                  <div :id="`tui-${item.id}-color-picker`"></div>
                </div>
                <!-- 画笔粗细 和 文字大小-->
                <div v-if="child.range" class="hiddenmenu">
                  <input
                    v-if="item.id === 'draw'"
                    v-model="range"
                    type="range"
                    min="10"
                    max="100"
                    @change="rangeChange"
                  />
                  <input
                    v-if="item.id === 'text'"
                    v-model="textRange"
                    max="240"
                    min="10"
                    type="range"
                    @change="textRangeChange"
                  />
                </div>
                <div v-if="child.textstyle" class="hiddenmenu">
                  <button
                    class="hiddenmenu-button"
                    @click="handleSubMenuClick('text-style-bold', $event)"
                  >
                    <b>Bold</b>
                  </button>
                  <button
                    class="hiddenmenu-button"
                    @click="handleSubMenuClick('text-style-italic', $event)"
                  >
                    <i>Italic</i>
                  </button>
                  <button
                    class="hiddenmenu-button"
                    @click="handleSubMenuClick('text-style-underline', $event)"
                  >
                    <u>Underline</u>
                  </button>
                </div>
              </li>
            </ul>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
export default {
  name: 'ImageEditor',
  data() {
    return {
      imageEditor: null,
      displayingSubMenu: null,
      displayingHiddenMenu: null,
      range: 50,
      textRange: 20,
      brushColorpicker: null,
      textColorpicker: null,
      activeId: null,
    }
  },
  computed: {
    bottomMenu() {
      return [
        {
          id: 'undo',
          label: 'Undo',
          disabled: true,
        },
        {
          id: 'redo',
          label: 'Redo',
          disabled: true,
        },
        {
          id: 'crop',
          label: ' Crop',
          children: [
            {
              id: 'apply',
              label: 'Apply',
            },
            {
              id: 'cancel',
              label: 'Cancel',
            },
          ],
        },
        {
          id: 'draw',
          label: 'Draw',
          children: [
            {
              id: 'free',
              label: 'Free',
            },
            {
              id: 'straight',
              label: 'Straight',
            },
            {
              id: 'range',
              label: 'Range',
              range: true,
            },
            {
              id: 'color',
              label: 'Color',
              colorpicker: true,
            },
          ],
        },
        {
          id: 'text',
          label: 'Text',
          children: [
            {
              id: 'add',
              label: 'addText',
            },
            {
              id: 'size',
              label: 'Textsize',
              range: true,
            },
            {
              id: 'style',
              label: 'TextStyle',
              textstyle: true,
            },
            {
              id: 'color',
              label: 'Color',
              colorpicker: true,
            },
          ],
        },
        {
          id: 'rotate',
          label: 'Rotate',
          children: [
            {
              id: 'just',
              label: 'Rotate +90',
            },
            {
              id: 'negative',
              label: 'Rotate -90',
            },
            {
              id: 'filpX',
              label: 'FlipX',
            },
            {
              id: 'filpY',
              label: 'FlipY',
            },
          ],
        },
      ]
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init() {
      this.imageEditor = new window.tui.ImageEditor(
        document.getElementById('tui-image-editor'),
        {
          cssMaxWidth: window.innerWidth,
          cssMaxHeight: window.innerHeight,
          selectionStyle: {
            cornerSize: 50,
            rotatingPointOffset: 100,
          },
        }
      )
      this.imageEditor
        .loadImageFromURL(
          'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024',
          'SampleImage'
        )
        .then(() => {
          this.imageEditor.clearUndoStack()
        })
      const that = this
      this.imageEditor.on({
        undoStackChanged(length) {
          const undo = document.getElementById('btn-undo')
          if (length) {
            undo.classList.remove('disabled')
          } else {
            undo.classList.add('disabled')
          }
        },
        redoStackChanged(length) {
          const redo = document.getElementById('btn-redo')
          if (length) {
            redo.classList.remove('disabled')
          } else {
            redo.classList.add('disabled')
          }
        },
        objectScaled(obj) {
          console.log('obj', obj)
          if (obj.type === 'text' || obj.type === 'i-text') {
            that.textRange = obj.fontSize
          }
        },
        objectActivated(obj) {
          console.log('obj', obj)
          that.activeId = obj.id
          // switch (obj.type) {
          //   case 'text':
          //   case 'i-text': {
          //     console.log('文字')
          //     const target = document.getElementById('btn-text')
          //     that.menuHide()
          //     that.handleMenuClick(target, 'text')
          //     break
          //   }
          //   case 'path':
          //   case 'line': {
          //     console.log('线')
          //     const target = document.getElementById('btn-draw')
          //     that.menuHide()
          //     that.handleMenuClick(target, 'draw')
          //     break
          //   }
          // }
        },
        mousedown(event, originPointer) {
          console.log(event, originPointer)
        },
        addText(pos) {
          console.log('pos', pos)
        },
      })
      this.brushColorpicker = window.tui.colorPicker.create({
        container: document.getElementById('tui-draw-color-picker'),
        color: '#000000',
      })
      this.brushColorpicker.on('selectColor', (e) => {
        this.imageEditor.setBrush({
          color: this.hexToRGBa(e.color, 0.5),
        })
      })
      this.textColorpicker = window.tui.colorPicker.create({
        container: document.getElementById('tui-text-color-picker'),
        color: '#000000',
      })
      this.textColorpicker.on('selectColor', (e) => {
        this.imageEditor.changeTextStyle(this.activeId, {
          fill: this.hexToRGBa(e.color, 0.8),
        })
      })
    },
    handleMenuClick(target, type) {
      this.imageEditor.deactivateAll()
      switch (type) {
        case 'undo': {
          // 撤销
          const flag = target.classList.contains('disabled')
          if (!flag) {
            this.imageEditor.undo()
          }
          break
        }
        case 'redo': {
          // 重置
          const flag = target.classList.contains('disabled')
          if (!flag) {
            this.imageEditor.redo()
          }
          break
        }
        case 'crop': // 裁剪
          this.imageEditor.startDrawingMode('CROPPER')
          break
      }
      this.menuShow(target)
    },
    handleSubMenuClick(type, event = null) {
      switch (type) {
        case 'crop-apply': // 应用裁剪
          this.imageEditor.crop(this.imageEditor.getCropzoneRect()).then(() => {
            this.imageEditor.stopDrawingMode()
            this.menuHide()
          })
          break
        case 'crop-cancel': // 取消裁剪
          this.imageEditor.stopDrawingMode()
          this.menuHide()
          break
        case 'draw-free': {
          // 椭圆线
          const settings = this.getBrushSettings()
          this.imageEditor.stopDrawingMode()
          this.imageEditor.startDrawingMode('FREE_DRAWING', settings)
          this.hiddenmenuShow(event.target)
          break
        }
        case 'draw-straight': {
          // 直线
          const settings = this.getBrushSettings()
          this.imageEditor.stopDrawingMode()
          this.imageEditor.startDrawingMode('LINE_DRAWING', settings)
          this.hiddenmenuShow(event.target)
          break
        }
        case 'draw-range':
        case 'draw-color': // 线颜色
        case 'text-size':
        case 'text-style':
        case 'text-color': {
          // 文字大小
          this.hiddenmenuShow(event.target)
          break
        }
        case 'text-add': {
          this.imageEditor.startDrawingMode('TEXT')
          const textColor = this.textColorpicker.getColor()
          const canvas = document.querySelector('.upper-canvas')
          console.log(canvas)
          this.imageEditor.addText('Double Click', {
            styles: {
              fontSize: this.textRange,
              color: this.hexToRGBa(textColor, 0.8),
            },
            position: {
              x: 150,
              y: 100,
            },
          })
          break
        }
        case 'rotate-just': // 旋转90度
          this.imageEditor.rotate(90)
          break
        case 'rotate-negative': // 旋转-90度
          this.imageEditor.rotate(-90)
          break
        case 'rotate-filpX': //  FilpX
          this.imageEditor.flipX()
          break
        case 'rotate-filpY': //  FilpY
          this.imageEditor.flipY()
          break
        case 'text-style-bold':
          this.imageEditor.changeTextStyle(this.activeId, {
            fontWeight: 'bold',
          })
          break
        case 'text-style-italic':
          this.imageEditor.changeTextStyle(this.activeId, {
            fontStyle: 'italic',
          })
          break
        case 'text-style-underline':
          this.imageEditor.changeTextStyle(this.activeId, {
            textDecoration: 'underline',
          })
          break
      }
    },
    getBrushSettings() {
      const brushColor = this.brushColorpicker.getColor()
      return {
        width: this.range,
        color: this.hexToRGBa(brushColor, 0.5),
      }
    },
    // 调整线的宽度
    rangeChange(e) {
      this.imageEditor.setBrush({
        width: e.target.value,
      })
    },
    hexToRGBa(hex, alpha) {
      var r = parseInt(hex.slice(1, 3), 16)
      var g = parseInt(hex.slice(3, 5), 16)
      var b = parseInt(hex.slice(5, 7), 16)
      var a = alpha || 1
      return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')'
    },
    // 调整文字的大小
    textRangeChange(e) {
      this.imageEditor.changeTextStyle(this.activeId, {
        fontSize: e.target.value,
      })
    },
    menuShow(target) {
      const subMenu = target.parentNode.querySelector('.submenu')
      if (subMenu) {
        this.displayingSubMenu = subMenu
        subMenu.classList.add('show')
      }
    },
    menuHide() {
      if (this.displayingSubMenu) {
        this.displayingSubMenu.classList.remove('show')
      }
      if (this.displayingHiddenMenu) {
        this.displayingHiddenMenu.classList.remove('show')
      }
      this.imageEditor.stopDrawingMode()
      this.imageEditor.deactivateAll()
    },
    hiddenmenuShow(target) {
      if (this.displayingHiddenMenu) {
        this.displayingHiddenMenu.classList.remove('show')
      }
      const menu = target.parentNode.querySelector('.hiddenmenu')
      if (menu) {
        this.displayingHiddenMenu = menu
        menu.classList.add('show')
      }
    },
  },
}
</script>
<style lang="less" scoped>
.tui-image-editor {
  width: 100%;
  height: 100vh;
  background-color: #383838;
}
.tui-image-editor-controls {
  &.mobile {
    display: block;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
  }
  .scrollable {
    display: inline-block;
    overflow-x: auto;
    width: 100%;
    height: 100%;
    white-space: nowrap;
    font-size: 0;
    background-color: #000;
    vertical-align: middle;
    padding-inline-start: 0px;
    &::-webkit-scrollbar {
      display: none;
      scrollbar-width: none;
      -ms-overflow-style: none;
    }
  }
  .no-scrollable {
    overflow-x: hidden;
  }
  .menu-item {
    display: inline-block;
    height: 50px;
    border-right: 1px solid #383838;
    background-color: #ddd;
    vertical-align: middle;
    .menu-button {
      min-width: 80px;
      height: 50px;
      border: none;
      vertical-align: middle;
      background-color: #000;
      color: #fff;
      font-size: 12px;
      font-weight: bold;
      outline: 0;
      white-space: pre-wrap;
      &.disabled {
        opacity: 0.8;
        color: #ccc;
        cursor: not-allowed; /* 禁用时的鼠标样式 */
      }
    }
  }

  .submenu-button {
    min-width: 80px;
    height: 50px;
    border: none;
    background-color: #ddd;
    vertical-align: middle;
  }
  .hiddenmenu-button {
    margin: 0 10px;
    padding: 5px;
    border: none;
    color: #fff;
    background-color: rgba(255, 255, 255, 0);
  }
  .submenu {
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    font-size: 0;
    &.show {
      display: block;
    }
    .scrollable {
      width: calc(100% - 30px);
    }
    .menu-item:last-child {
      margin-right: 50px;
    }
  }
  .hiddenmenu {
    position: absolute;
    display: none;
    padding: 40px;
    width: 100%;
    left: 0;
    bottom: 50px;
    background-color: rgba(0, 0, 0, 0.7);
    text-align: center;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    z-index: 9999;
    &.show {
      display: block;
    }
    .top {
      font-size: 12px;
      color: #fff;
      margin-bottom: 20px;
    }
  }
  .btn-prev {
    display: inline-block;
    width: 30px;
    height: 50px;
    background-color: #000;
    color: #fff;
    border: none;
    vertical-align: middle;
    i {
      font-size: 18px;
    }
  }
  .tui-colorpicker-container {
    display: inline-block;
  }
  .msg {
    position: absolute;
    margin-left: 50%;
    padding: 5px 10px;
    left: -86px;
    top: -50px;
    border-radius: 5px 5px;
    background-color: rgba(255, 255, 255, 0.5);
    font-size: 12px;
    &.hide {
      display: none;
    }
  }
}
.tui-image-editor-help-menu {
  display: none !important;
}
[id$='-color-picker'] {
  display: flex;
  justify-content: center;
}
::v-deep{
  .tui-image-editor-canvas-container{
    margin: 0 auto;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>
